<script setup lang="ts">
import { getOrderIdAPI, getPriceAPI } from '@/services/consult'
import { queryPatientAPI } from '@/services/user'
import { useConsultStore } from '@/stores'
import type { FeeResult } from '@/types/consult'
import type { PatientInfo } from '@/types/user'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import { onMounted, ref } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'

const store = useConsultStore()

// 获取患者信息
const patientInfo = ref<PatientInfo>()
const getPatientInfo = async () => {
  if (store.consultInfo.patientId) {
    const { data } = await queryPatientAPI(store.consultInfo.patientId)
    patientInfo.value = data
  }
}
const desc = ref(store.consultInfo.illnessDesc)

// 优惠券信息
const payInfo = ref<FeeResult>()
const getFeeResult = async () => {
  const { data } = await getPriceAPI({
    type: store.consultInfo.type,
    illnessType: store.consultInfo.illnessType
  })
  payInfo.value = data
}
const router = useRouter()
onMounted(async () => {
  // 3. 刷新页面的话，需要判断是否存在有问诊信息，如果没有了则不能发送请求，需要跳转到首页重新选择
  if (!store.consultInfo.type) {
    // 从问诊页面回退回来之后没有跳转到首页 ，需要添加 closeOnPopState
    return showDialog({
      title: '温馨提示',
      message: '问诊信息已置空，请重新选择！',
      closeOnPopstate: false
    }).then(() => {
      return router.push({ name: 'home' })
    })
  }
  getPatientInfo()
  getFeeResult()
})
// 底部同意协议
const checked = ref(true)
// 立即支付
const orderID = ref('')
const loading = ref(false)
const onSubmit = async () => {
  // 判断是否已经勾选我同意
  if (!checked.value) return showToast('请勾选我同意')
  loading.value = true
  // 获取支付订单信息
  const { data } = await getOrderIdAPI(store.consultInfo)
  orderID.value = data.id
  // 并将pinia中的订单相关信息清空
  store.clearConsultInfo()
  loading.value = false
  showBottom.value = true
}
const showBottom = ref(false)
// 支付方式
// 支付的相关操作
// 1. 点击灰色区域可以关闭弹出框，弹框提示是否关闭
const closeSheet = () => {
  return showConfirmDialog({
    title: '关闭支付',
    message: '您还没有支付，需要关闭吗？',
    confirmButtonText: '继续支付',
    cancelButtonText: '仍要关闭'
  })
    .then(() => {
      // 点击了继续支付，则阻止关闭
      return false
    })
    .catch(() => {
      orderID.value = '' // 因为在onBeforeRouteLeave钩子函数中进行了跳转拦截
      // 点击了取消，但是此时已经有订单号了，并且患者相关信息已经被清空，需要返回首页或者跳转到问诊记录中继续支付
      // ??? 这里为什么name跳转不过去
      // router.push('/user/consult')
      router.push({ name: 'ConsultRecord' })
      return true
    })
}
// 2. 如果已经生成了订单号后，回退需要进行拦截
onBeforeRouteLeave(() => {
  // 防止点击了立即支付后又点击浏览器的后退按钮，需要对这个回退进行阻止
  if (orderID.value) {
    return false
  }
})
// 4. 点击立即支付，将会从后台中获取支付的url地址
/* const pay = async () => {
  if (payWay.value === undefined) return showToast('请选择支付方式')
  if (payWay.value !== undefined && orderID.value) {
    showLoadingToast('正在跳转支付...')
    const { data } = await getPayAPI({
      paymentMethod: payWay.value,
      orderId: orderID.value,
      payCallback: 'http://localhost:5173/room'
    })
    location.href = data.payUrl
  }
} */
</script>

<template>
  <div class="pay-page">
    <DP-NavBar title="图文支付"></DP-NavBar>
    <div v-if="payInfo && patientInfo">
      <div class="title">
        <p color="font-size: 16px;">
          图文问诊<span> {{ payInfo.actualPayment }} </span>元
        </p>
      </div>
      <van-cell :border="false" class="pay-title">
        <template v-slot:title>
          <div class="consult">
            <p>极速问诊</p>
            <span>自动分配医生</span>
          </div>
        </template>
        <template v-slot:icon>
          <img src="@/assets/avatar-doctor.svg" />
        </template>
      </van-cell>
      <van-cell-group>
        <van-cell title="优惠券" :value="`-￥${payInfo.couponDeduction}`" />
        <van-cell title="积分抵扣" :value="`-￥${payInfo.pointDeduction}`" />
        <van-cell
          title="实付款"
          :value="`￥${payInfo.actualPayment}`"
          class="payment"
        />
      </van-cell-group>
      <van-cell
        class="pay-foot"
        title="患者信息"
        :value="`${patientInfo.name} | ${patientInfo.genderValue} | ${patientInfo.age}岁`"
      ></van-cell>
      <van-cell class="pay-title" title="病情描述" :label="desc"></van-cell>
      <div class="agree">
        <van-checkbox v-model="checked">
          <template v-slot:default>
            <span>我已同意</span>
            <a href="javascript:;" class="agree-ptotocal">支付协议</a>
          </template>
        </van-checkbox>
      </div>
      <van-submit-bar
        :price="payInfo.actualPayment * 100"
        text-align="left"
        :loading="loading"
        button-text="立即支付"
        button-type="primary"
        @submit="onSubmit"
      />
      <DP-Pay
        v-if="showBottom"
        v-model:show-bottom="showBottom"
        :orderID="orderID"
        :actual-payment="payInfo.actualPayment"
        :close-sheet="closeSheet"
        pay-callback="/room"
      ></DP-Pay>
    </div>
    <div v-else>
      <van-skeleton title :row="3" />
      <van-skeleton title :row="4" />
      <van-skeleton title :row="5" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.pay-page {
  margin-top: 46px;
  > .title {
    padding: 16px;
    padding-bottom: 0;
  }
  .pay-title {
    border-bottom: 1px solid var(--van-cell-border-color);
    span {
      color: #878887;
      font-size: 13px;
    }
    img {
      width: 38px;
      height: 38px;
      margin-right: 10px;
    }
  }
  .pay-foot {
    border-top: 15px solid #f5f5f7;
  }
  .agree {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 56px;
    .agree-ptotocal {
      color: var(--cp-primary);
      margin-left: 5px;
    }
  }
  .payment {
    ::v-deep() {
      .van-cell__value {
        color: var(--cp-price);
      }
    }
  }
  .van-submit-bar {
    position: fixed;
    bottom: 0;
    ::v-deep() {
      .van-submit-bar__price {
        font-weight: 500;
      }
      .van-button {
        width: 160px;
      }
    }
  }
}
</style>
